﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Luna;

namespace TextDataExtractor.DEML {
	
	public class DataPart : AbstractDataPart, IDataProvider {
		private Match matchResult;
		private Regex pattern;

		public string DataTemplate {
			get { return getArgument("template"); }
			set { Arguments["template"] = value; }
		}

		public Regex Pattern {
			get { return pattern != null ? pattern : (pattern = new Regex(DataTemplate, RegexOptions.Multiline | RegexOptions.Compiled)); }
		}

		public override int match(string input) {
			if (string.IsNullOrWhiteSpace(DataTemplate)) {
				MatchedText = input;
				IsSuccess = true;
				StartIndex = 0;
				EndIndex = input.Length - 1;
				return 1;
			}
			else {
				matchResult = Pattern.Match(input);
				IsSuccess = matchResult.Success;
				if (matchResult.Success) {
					StartIndex = matchResult.Index;
					EndIndex = StartIndex + matchResult.Length - 1;
					MatchedText = matchResult.Groups[0].Value;
					return 1;
				}
				else
					return 0;
			}
		}

		public object getDataItem(object idx) {
			if (IsSuccess) {
				int index = idx is int ? (int)idx : idx.ToString().convertTo<int>();
				if (index == 0) return MatchedText;
				else if (matchResult != null && index > 0 && index < matchResult.Groups.Count)
					return matchResult.Groups[index].Value;
			}
			return string.Empty;
		}

		public override void CopyTo(DemlElement target) {
			base.CopyTo(target);
			(target as DataPart).pattern = this.Pattern;
		}
	}
}
